package com.zzdn.mqtool.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.core.io.*;
import org.springframework.util.ResourceUtils;

import java.io.*;

@Component
public class LocalFileReadUtils {

    private static Logger logger = LoggerFactory.getLogger(LocalFileReadUtils.class);

    //相对路径
    private static String filePath = "/xmlTemplates/";

    public  String readXml(String tradeno){

        try {

            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if(!path.exists()) {
                path = new File("");
            }

            String fpath = path.getAbsolutePath() + filePath;

            logger.info("加载模板文件名： {} ", path.getAbsolutePath());

            File f = new File(fpath + tradeno +".xml");
            logger.info("加载模板文件名： {} ", f.getName());

            InputStream fi = new FileInputStream(f);

//            Resource resource = new ClassPathResource(filePath+tradeno+".xml");
//            File f = resource.getFile();
//            InputStream fi = new FileInputStream(f);
        //    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));

//            InputStream fi = this.getClass().getResourceAsStream(filePath+tradeno+".xml");
//            byte[] b = new byte[1024];
//            int readIndex;
//            String content = "";
//            while (-1 != (readIndex = fi.read(b, 0, b.length))) {
//                content += new  String(b,"GBK");
//            }

            byte[] b = new byte[(int) f.length()];
            fi.read(b, 0, (int) f.length());

            return new String(b,"GBK");

        }catch(Exception e){
            logger.info("加载模板文件失败！！ {}", e.getMessage());
        }

        return null;

    }

//    public static void main(String[] args){
//        System.out.println(readXml("1202"));
//
//    }

}
